package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品管理
 */
@Slf4j
@RestController
@RequestMapping("dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        //清理所有菜品的缓存数据 获取 redis 里面 所有以dish_开头的key
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /**
     * 菜品分页信息查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //构造分页构造器对象
        Page<Dish> pageinfo = new Page<>(page, pageSize);
        Page<DishDto> dishDtoPage = new Page<>();
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(name != null, Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(pageinfo, queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(pageinfo, dishDtoPage, "records");

        List<Dish> records = pageinfo.getRecords();

        /*
        pageinfo 对象中有 records这个属性 这个属性存放着我们所需要的数据,我们先把pageinfo除了record之外的全部属性的数据 拷贝到 dishDtoPage中
        再将dishDtoPage里面的records重新赋值  方法是: 将pageinfo中的records里面的内容 拷贝到 dishDto中 再根据dish表中对应的分类id
        去 分类表中 查询 分类的名字 最后在赋值 dishDto.setCategoryName(categoryName); 最后 dishDtoPage.setRecords(list);
         */
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId); //根据id拿到分类对象
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    /**
     * 查询对应菜品的信息 用作页面回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        if (dishDto != null) {
            return R.success(dishDto);
        }
        return R.error("没有查询到对应菜品的信息");
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        //清理所有菜品的缓存数据 获取 redis 里面 所有以dish_开头的key
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus();
        redisTemplate.delete(key);
        return R.success("成功修改菜品信息");
    }

    /**
     * 批量删除菜品和与之对应的口味
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    public R<String> delete(@RequestParam("ids") List<Long> ids) {
        dishService.removeByIds(ids);
        for (Long id : ids) {
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, id);
            dishFlavorService.remove(queryWrapper);
        }
        return R.success("成功删除菜品信息");
    }

    @PostMapping("/status/1")
    public R<String> Start_sale(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(1);
            dishService.updateById(dish);
        }
        return R.success("成功修改菜品状态");
    }

    @PostMapping("/status/0")
    public R<String> halt_sales(@RequestParam("ids") List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("成功修改菜品状态");
    }
    //public R<List<Dish>> list(@RequestParam("categoryId") Long categoryId)
    //queryWrapper.eq(Dish::getCategoryId,categoryId);

    /**
     * 根据条件查询对应的菜品数据
     *
     * @param dishDto
     * @return
     */
    /*@GetMapping("/list")
    public R<List<Dish>> list(Dish dish) {//大数据类型接收小数据
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //只查起售状态的菜
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件 Sort升序 UpdateTime降序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        return R.success(list);
    }*/
    @GetMapping("/list")
    public R<List<DishDto>> list(DishDto dishDto) {//大数据类型接收小数据
        List<DishDto> dishDtoList = null;
        //动态构造key
        String key = "dish_" + dishDto.getCategoryId() + "_" + dishDto.getStatus(); //dish_1397844391040167938_1
        //先从redis中获取缓存数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dishDto.getCategoryId() != null, Dish::getCategoryId, dishDto.getCategoryId());
        //封装查询条件 起售
        queryWrapper.eq(Dish::getStatus, 1);
        //添加排序条件 Sort升序 UpdateTime降序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //菜品基本信息列表(不包含口味)
        List<Dish> list = dishService.list(queryWrapper);
        //包含口味的菜品信息列表
        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto1 = new DishDto();
            BeanUtils.copyProperties(item, dishDto1);

            Long categoryId = item.getCategoryId();//分类id
            Category category = categoryService.getById(categoryId); //根据id拿到分类对象
            if (category != null) {
                String categoryName = category.getName();
                dishDto1.setCategoryName(categoryName);
            }
            //根据菜品id去菜品口味表里面拿到该菜品所对应的口味数据
            Long dishId = item.getId(); //菜品id
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorsList = dishFlavorService.list(queryWrapper1);
            //将dishDto里面的口味赋上数据
            dishDto1.setFlavors(dishFlavorsList);
            return dishDto1;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis 缓存时间为60分钟
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
